package jsyf.com.util;

import com.alibaba.fastjson.JSONObject;
import jsyf.com.constant.Const;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisCluster;

/**
 * @author: @张晓满 @Tupurp
 * @creat: 2017/12/6 16:12
 * description:    校验图片验证码手机验证码
 */
public class ValidatePhoneCodeAndImageCode {


    /**
     * @param jsonData 封装了手机号，图片验证码，手机验证码，图片验证码在缓存中的key
     * @Description: 校验图片验证码手机验证码  <br/>
     * @return: void
     * @throw:
     * @author: @张晓满 @Tupurp
     * @createTime: 2017/12/6 16:14
     * @Version: V1.0.0
     */
    public static String validateCode(JSONObject jsonData,JedisCluster jedisCluster){
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        /*获取参数*/
        String imageCodeKey = jsonParam.getString("imageCodeKey");
        String imageCodeValue = jsonParam.getString("imgCode");
        String phoneNumber = jsonParam.getString("phoneNumber");
        String phoneCode = jsonParam.getString("phoneCode");
        String result = "";
        if ( StringUtils.isBlank(phoneNumber)) {
            result = BaseUtils.errorrRespond(1,"手机号不可以为空!");
            return  result;
        }
        if (StringUtils.isBlank(imageCodeValue)) {
            result = BaseUtils.errorrRespond(2,"图片验证码不可以为空!");
            return  result;
        }
        if (StringUtils.isBlank(phoneCode)) {
            result = BaseUtils.errorrRespond(3,"手机验证码不可以为空!");
            return  result;
        }
        /*redis中key*/
        String imageCodeKeyRedis = imageCodeKey + Const.IMAGE_CODE_POSTFIX;
        String phoneNumberRedis = phoneNumber + Const.PHONE_CODE_POSTFIX;
        String imageCodeValueRedis = jedisCluster.get(imageCodeKeyRedis);
        /*判断和redis中的值是否一致*/
        if (StringUtils.isBlank(imageCodeValueRedis)
                || !imageCodeValueRedis.equalsIgnoreCase(imageCodeValue.toUpperCase())) {
            result = BaseUtils.errorrRespond(2,"图片验证码不正确!");
        } else if (StringUtils.isBlank(jedisCluster.get(phoneNumberRedis)) || !jedisCluster.get(phoneNumberRedis).equals(phoneCode)) {
            result = BaseUtils.errorrRespond(3,"手机验证码不正确!");
        } else {
            result = BaseUtils.succsessObjRespond();
        }

        return  result;
    }
}
